/*
** client.c for  in /home/gomes_m//workzone/ftp
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Wed Apr 10 15:00:14 2013 mickael gomes
** Last update Thu Apr 11 14:06:21 2013 mickael gomes
*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

char			*get_word(int fd)
{
  char			*buff;
  int			len;

  buff = malloc(2048 * sizeof(char));
  len = read(0, buff, 2048);
  buff[len] = 0;
  write(fd, buff, strlen(buff));
  return (buff);
}

int			main(int ac, char **av)
{
  struct protoent	*pe;
  struct sockaddr_in	s_in;
  int			fd;
  int			port;
  char			*ip;
  char			*buff[512];
  int			len;
  int			check;
  char			*lol;

  if (ac != 3)
    return (1);
  ip = av[1];
  port = atoi(av[2]);
  pe = getprotobyname("TCP");
  if (!pe)
    return (1);
  fd = socket(AF_INET, SOCK_STREAM, pe->p_proto);
  if (fd == -1)
    return (1);
  s_in.sin_family = AF_INET;
  s_in.sin_port = htons(port);
  s_in.sin_addr.s_addr = inet_addr(ip);
  if (connect(fd, (struct sockaddr *)&s_in, sizeof(s_in)) == -1)
    {
      if (close(fd) == -1)
	return (1);
      return (1);
    }
  while (42)
    {
      lol = get_word(fd);
      check = strcmp(lol, "quit\n");
      if (check == 0)
	{
	  if (close(fd) == -1)
	    return (1);
	  exit(EXIT_SUCCESS);
	}
      if (!strcmp(lol, "ls\n") || !strcmp(lol, "pwd\n"))
	{
	  len = read(fd, buff, 511);
	  buff[len] = 0;
	  write(1, buff, len);
	}
    }
  return (0);
}
